package com.katesoft.scale4j.rttp.jobs;

import static com.katesoft.scale4j.rttp.internal.IRttpHazelcastRefs.JOB_PARAMS_INCREMENTER;
import net.jcip.annotations.ThreadSafe;

import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersIncrementer;

import com.hazelcast.core.IMap;
import com.hazelcast.core.IdGenerator;
import com.katesoft.scale4j.rttp.client.IClusterInstanceAware.ClusterInstanceAwareBean;

/**
 * this class will add unique run id for each job execution.
 * 
 * @author kate2007
 */
@ThreadSafe
public class DistributedJobParametersIncrementer extends ClusterInstanceAwareBean implements
         JobParametersIncrementer {

   @Override
   public JobParameters getNext(JobParameters parameters) {
      String jobName = parameters.getString(JobsUtility.JOB_NAME);
      long l = System.currentTimeMillis();
      if (getInstance().getLifecycleService().isRunning()) {
         IMap<Object, Object> map = getInstance().getMap(JOB_PARAMS_INCREMENTER);
         IdGenerator idGenerator = getInstance().getIdGenerator("rttp.jobs." + jobName);
         Object obj = map.get(jobName);
         l = idGenerator.newId();
         if (obj == null) {
            map.putIfAbsent(jobName, l);
         } else {
            map.replace(jobName, l);
         }
         logger.debug("added run.id=%s to job parameters", l);
      }
      return new JobParametersBuilder(parameters).addLong("run.id", l).toJobParameters();
   }
}
